// pages/chat/chat.ts
import { getStatus } from '../../api/guide';
import { isLogin } from '../../utils/login'
import { getTrainTask, reviewTask, trainTask } from '../../api/train'
import { debounce } from '../../utils/debounce'

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    detail: {
      name: '',
      questionVo: {}
    },
    isShow: false,
    scores: [],
    showRejectModal: false,
    showFinishModal: false,
    showRejectedModal: false,
    showFinishedModal: false,
    showRejectInputModal: false,
    tips: ['内容有误', '内容不精准', '缺乏可操作性', '共情性低'],
    currentTipIndex: -1,
    rejectReason: '',
    form: null,
    editFlag: {
      answer: false,
      explain: false,
      name: false,
      disease: false,
      change: false,
      diagnosisTime: false,
      hospital: false,
      treatment: false,
      programme: false
    },
  },

  showEditor(e){
    const { flag } = e.currentTarget.dataset;
    const editFlag: any = {};
    editFlag[flag] = true;
    this.setData({
      editFlag: editFlag
    })
  },

  backToCase(){
    wx.navigateBack({
      delta: 1 
    });
  },

  onLoad() {
    const _self = this;
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function(data) {
      if(data){
        getTrainTask(data.id).then(res => {
          if(res.data){
            const list = res.data.scoreRuleList
            let scores = list && list.map(item => item.score)

            if(!scores || scores.length === 0){
              scores = new Array(list.length).fill(0)
            }

            _self.setData({
              detail: {
                ...res.data,
                nextList: data.nextList
              },
              scores
            })

            if(res.data.status === '3' && res.data.type === '0'){
              _self.setData({
                showRejectModal: true
              })
            }
          }
        })
      }
      // detail.detail = detail.detail.replace(/\n/g, '<br />').replace(/\[(.*?)\]/g, '<p><h3>$1</h3></p>')
    })
  },

  previewPdf(e){
    const fileUrl = e.currentTarget.dataset.file
    wx.downloadFile({
      url: fileUrl,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      }
    })
  },

  onInputRejectReason: function(e){
    this.setData({
      rejectReason: e.detail.value
    });
  },

  onStarTap: function(e) {
    const {index, num} = e.currentTarget.dataset;
    const array = [...this.data.scores];
    array[index] = num + 1;
    this.setData({
      scores: array
    })
  },

  onRejectTipTap: function(e){
    const index = e.currentTarget.dataset.index;
    console.log('---点击输出:', index)
    if (this.data.currentTipIndex === index) {
      this.setData({
        currentTipIndex: -1
      });
    } else {
      this.setData({
        currentTipIndex: index
      });
    }
  },

  onSubmit(){
    const type = this.data.detail.type
    const isReview = type === '1'
    if(isReview){
      reviewTask({
        id: this.data.detail.id,
        status: '2'
      }).then(res => {
        if(res.code === 200){
          const list = this.data.detail.nextList;
          if(list && list.length > 1){
            this.setData({
              showFinishModal: true
            })
          }else{
            this.setData({
              showFinishedModal: true
            })
          }
        }
      })
    }else{
      if(this.data.scores.indexOf(0) > -1){
        wx.showToast({
          title: '请评分后提交',
          icon: 'none'
        });
        return 
      }

      const d = this.data.detail.details
      let content = {}

      if(this.data.detail.questionType === '0'){
        content = {
          answer: d.answer
        }
      }else if(this.data.detail.questionType === '1'){
        content = {
          explain: d.explain
        }
      }else if(this.data.detail.questionType === '2'){
        content = {
          change: d.change,
          diagnosisTime: d.diagnosisTime,
          disease: d.disease,
          hospital: d.hospital,
          labelList: d.labelList,
          programme: d.programme,
          treatment: d.treatment
        }
      }

      const data = {
        ...content,
        ...this.data.form
      }

      const scoreRuleList = this.data.scores.map((item, index) => {
        return {
          id: this.data.detail.scoreRuleList[index].id,
          name: this.data.detail.scoreRuleList[index].name,
          score: item
        }
      })
      trainTask({
        id: this.data.detail.id,
        projectId: this.data.detail.projectId,
        scoreRuleList,
        content: JSON.stringify(data)
      }).then(res => {
        if(res.code === 200){
          const list = this.data.detail.nextList;
          if(list && list.length > 1){
            this.setData({
              showFinishModal: true
            })
          }else{
            this.setData({
              showFinishedModal: true
            })
          }
        }
      })
    }
  },

  handleInput: debounce((e: any, context: any) => {
    const value = e.detail.value;
    const { flag } = e.currentTarget.dataset
    const f: any = {}
    f[flag] = value;

    context.setData({
      form: {
        ...context.data.form,
        ...f
      }
    })
  }),

  onReject(){
    this.setData({
      showRejectInputModal: true
    })
  },

  next(){
    let list = this.data.detail.nextList.filter(item => item !== this.data.detail.id);
    const nextId = list[0]
    if(typeof nextId !== 'undefined'){
      getTrainTask(nextId).then(res => {
        if(res.data){
          const scoreRuleList = res.data.scoreRuleList
          let scores = scoreRuleList && scoreRuleList.map(item => item.score)

          if(!scores || scores.length === 0){
            scores = new Array(scoreRuleList.length).fill(0)
          }

          this.setData({
            detail: {
              ...res.data,
              nextList: list
            },
            scores: scores,
            showFinishModal: false,
            showRejectedModal: false,
            rejectReason: '',
            selectedTips: [],
            currentTipIndex: -1
          })
        }
      })
    }
  },
  retry(){
    this.setData({
      showRejectModal: false
    })
  },
  done(){
    wx.navigateBack({
      delta: 2
    });
  },
  reject(){
    let reason = this.data.rejectReason
    // 优先用单选
    if(this.data.currentTipIndex !== -1){
      reason = this.data.tips[this.data.currentTipIndex]
    }

    if(!reason){
      wx.showToast({
        title: '请选择驳回理由',
        icon: 'none'
      });
      return
    }
    reviewTask({
      id: this.data.detail.id,
      status: '3',
      reviewRemark: reason
    }).then(res => {
      if(res.code === 200){
        if(this.data.detail.nextList.length <= 1){
          this.setData({
            showRejectInputModal: false,
            showFinishedModal: true
          })
        }else{
          this.setData({
            showRejectInputModal: false,
            showRejectedModal: true
          })
        }
      }
    })
  },

  closeModal(){

  },

  onShow(){
    if(isLogin()){
      getStatus().then(res => {
        if(res.data){
          this.setData({
            isShow: res.data.status === '0'
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})